package com.itc.bi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itc.bi.api.dto.DataSetDto;
import com.itc.bi.api.dto.OrderDto;
import com.itc.bi.api.dto.ParamsDto;
import com.itc.bi.api.vo.DataSetVO;
import com.itc.bi.entity.DataProcessEntity;
import com.itc.bi.entity.DataSetColumnEntity;
import com.itc.bi.mapper.BigScreenImageMapper;
import com.itc.bi.service.DataProcessService;
import com.itc.bi.service.DataSetColumnService;
import com.itc.bi.service.FeignClientService;
import com.itc.bi.utils.APIQueryUtil;
import com.itc.bi.utils.StringBuildUtil;
import com.itc.bi.vo.bigScreenVO.ApiPageDataVO;
import com.itc.bi.vo.bigScreenVO.ProDirDataSetVO;
import com.itc.bi.vo.excelVo.HeardVO;
import com.itc.common.core.exception.ServiceException;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:  feign接口
 * @Version: 1.0
 */
@Service
public class FeignClientServiceImpl implements FeignClientService {

    @Autowired
    private ClickHouseJDBCService clickHouseJDBCService;
    @Autowired
    private DataSetColumnService dataSetColumnService;

    @Autowired
    private BigScreenImageMapper bigScreenImageMapper;

    /**
     * 获取数据
     * @param dto
     * @return
     */
    @Override
    public DataSetVO query(DataSetDto dto) {
        if(null == dto.getParams()){
            dto.setParams(new ArrayList<>());
        }
        if(null == dto.getOrders()){
            dto.setOrders(new ArrayList<>());
        }
        Assert.notNull(dto.getDataSetId(),"数据集ID不能为空");

        ProDirDataSetVO vo = bigScreenImageMapper.getProDirDataSetById(dto.getDataSetId());
        if(null == vo){
            throw new ServiceException("数据集不存在");
        }

        //每页大小最大值为
        Integer pageSize = dto.getPageSize();
        if(null == pageSize || pageSize < 1){
            pageSize = 10;
        }else if(pageSize >1000){
            throw new ServiceException("分页大小最大1000");
        }
        Integer pageIndex = dto.getPageIndex();
        if(null == pageIndex || pageIndex < 1){
            pageIndex = 1;
        }

        List<DataSetColumnEntity> columnList = dataSetColumnService.list(Wrappers.lambdaQuery(DataSetColumnEntity.class).eq(DataSetColumnEntity::getDataSetId, dto.getDataSetId()));
        Map<String,String> columnToTypeMap = columnList.stream().collect(Collectors.toMap(DataSetColumnEntity::getColumnName,DataSetColumnEntity::getColumnType));

        for(ParamsDto item : dto.getParams()){
            if(!columnToTypeMap.containsKey(item.getColumnName())){
                throw new ServiceException(String.format("字段 %s 不存在",item.getColumnName()));
            }
        }

        for(OrderDto item : dto.getOrders()){
            if(!columnToTypeMap.containsKey(item.getColumnName())){
                throw new ServiceException(String.format("字段 %s 不存在",item.getColumnName()));
            }
        }

        StringBuilder sqlBuilder = new StringBuilder("select ");
        sqlBuilder.append(columnToTypeMap.keySet().stream().collect(Collectors.joining(",")))
                .append(" from ").append(vo.getTableName());
        StringBuffer where = new StringBuffer();
        for (ParamsDto item : dto.getParams()) {
            if(where.length()>0){
                where.append(" and ");
            }else{
                where.append(" where ");
            }
            where.append(item.getExp());
        }
        sqlBuilder.append(where);

        StringBuffer order = new StringBuffer();
        for (OrderDto item : dto.getOrders()) {
            if(order.length()>0){
                order.append(",");
            }else{
                order.append(" order by ");
            }
            order.append(item.getColumnName());
            if(item.isAsc()){
                order.append(" asc");
            }else{
                order.append(" desc");
            }
        }
        sqlBuilder.append(order);

        sqlBuilder.append(" limit ").append((pageIndex-1)*pageSize)
                .append(",").append(pageSize);


        List<LinkedHashMap<String, Object>> data = clickHouseJDBCService.queryTableBySqlNotRemove(sqlBuilder.toString());
        sqlBuilder.setLength(0);
        sqlBuilder.append("select * from ")
                .append(vo.getTableName())
                .append(where);
        Long totalSize = clickHouseJDBCService.getTableSizeSql(sqlBuilder.toString());
        Long pageNum = (long)Math.ceil(totalSize/(double)pageSize);
        DataSetVO dataSetVO = new DataSetVO();
        dataSetVO.setData(data);
        dataSetVO.setPageTotalNumber(pageNum);
        return dataSetVO;
    }

    /**
     * 获取数据集数据项
     * @param dataSetId
     * @return
     */
    @Override
    public List<HeardVO> columnsByDataSetId(Long dataSetId){
        List<HeardVO> columns = new ArrayList<>();
        List<DataSetColumnEntity> dataSetColumnEntities = dataSetColumnService.columnListById(dataSetId);
        if(dataSetColumnEntities!=null && dataSetColumnEntities.size()>0) {
            for (DataSetColumnEntity dataSetColumnEntity : dataSetColumnEntities){
                columns.add(new HeardVO(dataSetColumnEntity.getColumnName(),dataSetColumnEntity.getColumnComment(),dataSetColumnEntity.getColumnType()));
            }
        }
        return columns;
    }
}
